package com.agricultural.machine.messaging;

import com.agricultural.machine.common.AbstractMachine;
import com.agricultural.machine.common.IMachine;
import com.agricultural.machine.factory.MachineFactory;
import com.agricultural.machine.logging.Logger;

import java.util.ArrayList;
import java.util.List;

/**
 * 消息代理类 - 处理农机间通信
 */
public class MessageBroker {
    private static MessageBroker instance;
    private final List<Message> messageHistory;
    private final Logger logger;
    private final MachineFactory machineFactory;
    
    private MessageBroker() {
        this.messageHistory = new ArrayList<>();
        this.logger = Logger.getInstance();
        this.machineFactory = MachineFactory.getInstance();
    }
    
    public static synchronized MessageBroker getInstance() {
        if (instance == null) {
            instance = new MessageBroker();
        }
        return instance;
    }
    
    /**
     * 发送消息
     */
    public void sendMessage(Message message) {
        // 记录消息
        messageHistory.add(message);
        logger.info("MessageBroker", "消息已发送: " + message);
        
        // 投递消息
        deliverMessage(message);
    }
    
    /**
     * 投递消息到目标农机
     */
    private void deliverMessage(Message message) {
        if (message.isBroadcast()) {
            // 广播消息发送给所有农机（除了发送者）
            machineFactory.getAllMachines().values().stream()
                    .filter(machine -> !machine.getMachineId().equals(message.getSenderId()))
                    .forEach(machine -> {
                        if (machine instanceof AbstractMachine) {
                            ((AbstractMachine) machine).receiveMessage(message);
                        }
                    });
        } else {
            // 定向消息只发送给特定接收者
            IMachine machine = machineFactory.getMachine(message.getReceiverId());
            if (machine != null && machine instanceof AbstractMachine) {
                ((AbstractMachine) machine).receiveMessage(message);
            }
        }
    }
    
    /**
     * 获取消息历史记录
     */
    public List<Message> getMessageHistory() {
        return new ArrayList<>(messageHistory);
    }
    
    /**
     * 清除消息历史记录
     */
    public void clearMessageHistory() {
        messageHistory.clear();
        logger.info("MessageBroker", "消息历史记录已清除");
    }
} 